<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../react18/react.development.js"></script>
    <script src="../react18/react-dom.development.js"></script>
    <script src="../react18/babel.min.js"></script>
</head>
<body>
    <button id="btn">添加水果</button>
    <div id="app"></div>

    <script type="text/babel">
      //因为如果乱序添加时候，还是会重新全部渲染，可以用一个key来标记元素，这样虚拟DOM对比时不会全部重新渲染

      //数据传输时，每个数据有个id属性，且不重复
        const arr = [
          {id:'001',name:'西瓜'},
          {id:'002',name:'菠萝'},
          {id:'003',name:'橘子'},
          {id:'004',name:'香蕉'},
        ]
        //创建虚拟DOM
        const vDOM = (
            <div>
                <h1>水果名</h1>
                <ul>
                  {
                    arr.map(item=>(<li key={item.id}>{item.name}</li>))
                  }
                </ul>
            </div>
        )

        const root = ReactDOM.createRoot(document.getElementById('app'))
        root.render(vDOM)
        
        // 给按钮绑定点击事件
        const oBtn = document.getElementById('btn');   
        let i = 0;
        oBtn.onclick = function(){
          
            //给数组末尾添加一个值
            arr.unshift({id:Date.now(),name:'苹果'+i++})
            const vDOM = (
            <div>
                <h1>水果名</h1>
                <ul>
                  {
                    arr.map(item=>(<li key={item.id}>{item.name}</li>))
                  }
                </ul>
            </div>
        )
        root.render(vDOM)
        }
    </script>
</body>
</html>